package com.qipay.security.sign.filter;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Cp;
import com.qipay.cp.CpService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.JWTUser;
import com.qipay.security.sign.service.SignService;
import com.qipay.utils.RequestUtils;
import com.qipay.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class SignTokenFilter extends OncePerRequestFilter {

    @Autowired
    SignService signService;
    @Autowired
    CpService cpService;

    @Value("${api.response.sign.name}")
    private String sigKey;

    private List<String> urls = new ArrayList<>();

    public SignTokenFilter(String... url) {
        Collections.addAll(urls, url.clone());
    }

    private JWTUser getLoginUser(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            JWTUser userImpl =
                    (JWTUser) authentication.getPrincipal();
            return userImpl;
        }
        return null;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            Map<String, Object> params = RequestUtils.getRequestParams(httpServletRequest);
            logger.info("request from " + httpServletRequest.getRequestURI() + ", request body:" + params);

            Object mch_id = params.get("mch_id");
            if(mch_id==null){
                errorResponse(httpServletResponse,ApiStatusEnum.ARGUMENT_REQUEST);
                return;
            }
            Cp cp = cpService.getOneById(Long.valueOf(mch_id.toString()));
            httpServletRequest.setAttribute("cpSecretId",cp.getSecretId());
            String fromSig = params.get(sigKey).toString();
            String mySig = signService.getSign(params, cp.getSecretId(), sigKey);
            if (!StringUtils.equals(fromSig, mySig)) {
                logger.warn("签名不一致:fromSig:" + fromSig + ", mysig:" + mySig);
                errorResponse(httpServletResponse,ApiStatusEnum.SIGN_ERR);
                return;
            }
            httpServletRequest.setAttribute("params", params);
        } catch (Exception e) {
            errorResponse(httpServletResponse,ApiStatusEnum.ARGUMENT_ERR);
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void errorResponse(HttpServletResponse response,ApiStatusEnum apiStatusEnum){
        response.setStatus(HttpStatus.SC_OK);
        Map<String, Object> result = ResultUtils.createStatusResult(apiStatusEnum.getCode().toString()
                , apiStatusEnum.getInfo());
        response.setContentType("application/json;charset=UTF-8");
        try{
            response.getWriter().append(JSONObject.toJSONString(result));
        }catch (Exception e){

        }
    }

    private boolean isFilterUrl(HttpServletRequest request) {
        String ctxPath = request.getServletPath();
        return urls.stream().anyMatch(p -> {
            return ctxPath.startsWith(p);
        });
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return !isFilterUrl(request);
    }
}
